export const getParentIdList = <T extends { [x: string]: string }>(
  idName: string,
  parentIdName: string,
  parentId: string,
  nodes: T[],
) => {
  let arr: string[] = [];
  const fn: (parentId: string, nodes: T[]) => void = (parentId, nodes) => {
    for (let i = 0; i < nodes.length; i++) {
      if (nodes[i][idName] == parentId) {
        arr.push(nodes[i][idName]);
        return fn(nodes[i][parentIdName], nodes);
      }
    }
  };
  fn(parentId, nodes);
  return arr;
};
interface DefaultTransformType<T> {
  name: string;
  children: T[];
}
export default function <T extends DefaultTransformType<T>>(
  nodes: any[],
  id: string,
  parentId?: string,
  renderTitle?: (item: T) => any,
) {
  const map: any = {};
  const root = [];
  for (let i = 0; i < nodes.length; i++) {
    nodes[i].key = nodes[i][id];
    nodes[i].title = renderTitle
      ? renderTitle(nodes[i])
      : nodes[i].title
      ? nodes[i].title
      : `${nodes[i].name}[${nodes[i][id]}]`;
    nodes[i].label = nodes[i].title;
    nodes[i].value = nodes[i].key;
    const node = nodes[i];
    const nodeId = node[id];
    map[nodeId] = i;
  }
  for (let i = 0; i < nodes.length; i++) {
    const node = nodes[i];
    // if (!parentId) return;
    const nodeParent = parentId ? node[parentId] : '';
    const parentIndex = map[nodeParent];
    if (parentIndex != 0 && !parentIndex) {
      root.push(node);
    } else {
      nodes[parentIndex].children = nodes[parentIndex].children || [];
      nodes[parentIndex].children?.push(node);
    }
  }
  return root;
}

export const  getPathByKey = (curKey, data) => {
  /** 存放搜索到的树节点到顶部节点的路径节点 */
  let result = [];
  /**
   * 路径节点追踪
   * @param {*} curKey 树节点标识的值
   * @param {array} path 存放搜索到的树节点到顶部节点的路径节点
   * @param {*} data 树
   * @returns undefined
   */
  let traverse = (curKey, path, data) => {
    // 树为空时，不执行函数
    if (data.length === 0) {
      return;
    }

    // 遍历存放树的数组
    for (let item of data) {
      // 遍历的数组元素存入path参数数组中
      path.push(item);
      // 如果目的节点的id值等于当前遍历元素的节点id值
      if (item.key === curKey || item._key === curKey ) {
        // 把获取到的节点路径数组path赋值到result数组
        result = JSON.parse(JSON.stringify(path));
        return;
      }

      // 当前元素的children是数组
      const children = Array.isArray(item.children) ? item.children : Array.isArray(item.childrenList)? item.childrenList: [];
      // 递归遍历子数组内容
      traverse(curKey, path, children);
      // 利用回溯思想，当没有在当前叶树找到目的节点，依次删除存入到的path数组路径
      path.pop();
    }
  };
  traverse(curKey, [], data);
  // 返回找到的树节点路径
  return result;
};

export const transformTreeToArray = (list) =>{
  return list.reduce((res,node) => {
      res.push({...node})
      if(node.children) res = res.concat(transformTreeToArray(node.children));
      return res
  }, [])
}
